package com.ldk.api.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import com.ldk.api.ApiVersion;
import com.ldk.api.CheckToken;
import com.ldk.api.ErrorCode;
import com.ldk.api.FileItem;
import com.ldk.api.RequestPlatform;
import com.ldk.api.ResponseObject;
import com.ldk.api.ResponseResult;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.Driver;
import com.ldk.framework.entity.LostOrder;
import com.ldk.framework.entity.LostOrderImages;
import com.ldk.framework.entity.User;
import com.ldk.framework.enums.LostOrderStatus;
import com.ldk.framework.enums.TripNoType;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.ILostOrderService;
import com.ldk.framework.service.IUserService;

/**
 * 失物招领模块
 * @author xiangwl
 * 2017年2月24日
 * com.ldk.api.handler
 * LostRequestHandler
 */
public class LostRequestHandler extends BaseRequestHandler {
	
	@Autowired
	private ILostOrderService lostOrderService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IDriverService driverService;
	/**
	 * 发布失物招领订单
	 * @param parms
	 * @param serviceCode 失物招领服务业务代码06
	 * @param openId openId
	 * @param goodsName 物品名称
	 * @param contact 联系方式
	 * @param platform 平台
	 * @return
	 */
	@ApiVersion(value={1})
	@CheckToken(check=true,tokenKey="openId",platform=RequestPlatform.client)
	public ResponseObject publish(Map<String, Object> parms){
		ResponseObject response = ResponseResult.create("express", "publish");
		//参数验证
		if(!checkRequireParms(parms,"fileList","serviceCode", "openId","goodsName","contact","platform")){
			return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
		}
		String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
		String openId = ConvertUtil.parseString(parms.get("openId"));
		String goodsName = ConvertUtil.parseString(parms.get("goodsName"));
		String contact = ConvertUtil.parseString(parms.get("contact"));
		String platform = ConvertUtil.parseString(parms.get("platform"));
		//获取当前模块的业务代码
		String curServiceCode = getServiceCode("失物招领");
		if(StringUtils.isBlank(serviceCode)){
			return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_EMPTY);
		}
		if(!serviceCode.equals(curServiceCode)){
			return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_ERROR);
		}
		if(StringUtils.isBlank(openId)){
			return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
		}
		if(StringUtils.isBlank(goodsName)){
			return ResponseResult.exception(response, ErrorCode.LOST_GOODS_NAME_EMPTY);
		}
		if(StringUtils.isBlank(contact)){
			return ResponseResult.exception(response, ErrorCode.LOST_CONTACT_EMPTY);
		}
		if(StringUtils.isBlank(platform)){
			return ResponseResult.exception(response, ErrorCode.PLATFORM_EMPTY);
		}
		//用户端
		if("1".equals(platform) || "2".equals(platform)){
			//验证用户是否存在
			User user = userService.getUserByOpenId("", openId);
			if(user == null){
				return ResponseResult.exception(response, ErrorCode.USER_NOT_EXIST);
			}
		}
		else if("4".equals(platform) || "8".equals(platform)){
			Driver driver = driverService.getDriverByOpenId("", openId);
			if(driver == null){
				return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
			}
		}
		else{
			return ResponseResult.exception(response, ErrorCode.PLATFORM_ERROR);
		}
		List<FileItem> fileList = null;
		if(parms.get("fileList") !=  null){
			try{
				@SuppressWarnings("unchecked")
				List<FileItem> list = (List<FileItem>)parms.get("fileList");
				fileList = list;
			}
			catch(Exception e){
				logger.error(e.getMessage());
			}
		}
		if(fileList == null || fileList.isEmpty() ){
			return ResponseResult.exception(response, ErrorCode.LOST_GOODS_IMAGE_EMPTY);
		}
		String orderNo = SystemUtil.generateOrderNo(TripNoType.SW.getPrefix());
		
		List<LostOrderImages> images = new ArrayList<LostOrderImages>();
		for (FileItem fileItem : fileList) {
			if(StringUtils.isBlank(fileItem.getFileFullUrl()))
				continue;
			LostOrderImages image = new LostOrderImages();
			image.setOrderNo(orderNo);
			image.setImage(fileItem.getFileFullUrl());
			images.add(image);
		}
		LostOrder entity = new LostOrder();
		entity.setOrderNo(orderNo);
		entity.setPublisher(openId);
		entity.setGoodsName(goodsName);
		entity.setContact(contact);
		entity.setPlatform(platform);
		entity.setStatus(LostOrderStatus.Publish.getValue());
		entity.setCreateTime(SystemUtil.getAllSeconds());
		
		Boolean success = false;
		try{
			success = lostOrderService.publish("", entity, images);
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(success){
			response = ResponseResult.success(response, "发布成功");
		}
		else{
			response = ResponseResult.exception(response, ErrorCode.LOST_PUBLISH_ORDER_FAILED);
		}
		
		return response;
	}
	
	/**
	 * 搜索失物招领订单
	 * @param parms
	 * @param searchKeys 搜索关键字
	 * @param openId 用户openId，如果不为空表示搜索属于自己发布的失物招领
	 * @param self 搜索自己的失物招领订单true是自己的false全部
	 * @param status 状态1发布2完成3全部
	 * @param pageIndex 页索引
	 * @param pageSize 每页显示的条数
	 * @return
	 */
	@ApiVersion(value={1})
	public ResponseObject search(Map<String, Object> parms){
		ResponseObject response = ResponseResult.create("lost", "search");
		//参数验证
		if(!checkRequireParms(parms,"searchKeys", "openId", "self" ,"status", "pageIndex", "pageSize")){
			return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
		}
		String searchKeys = ConvertUtil.parseString(parms.get("searchKeys"));
		String openId = ConvertUtil.parseString(parms.get("openId"));
		Boolean self = ConvertUtil.parseBoolean(parms.get("self"));
		int status = ConvertUtil.parseInt(parms.get("status"));
		int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
		int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
		pageIndex = Math.max(pageIndex, 1);
		pageSize = Math.max(pageSize, 1);
		int offset = (pageIndex - 1) * pageSize;
		

		LostOrder query = new LostOrder();
		String queryKeys = "";
		//搜索关键字大于2个字符再分词
		if(!StringUtils.isBlank(searchKeys)  && searchKeys.length() > 2){
			List<Term>  termList = ToAnalysis.parse(searchKeys);
			
			for (Term term : termList) {
				queryKeys += String.format("%s ", term.getName());
			}
		}
		else{
			queryKeys = searchKeys;
		}
		if(StringUtils.isBlank(queryKeys)){
			queryKeys = queryKeys.trim();
		}
		query.setGoodsName(queryKeys);
		query.setStatus(status);
		if(self && !StringUtils.isBlank(openId)){
			query.setPublisher(openId);
		}
		Sort sort = new Sort(Direction.DESC, "create_time");
		CustomPageable pageable = new CustomPageable(offset, pageSize, sort);
		List<LostOrder> result = lostOrderService.selectList("", query, pageable);
		if(result == null){
			response = ResponseResult.exception(response, ErrorCode.LOST_ORDER_EMPTY);
		}
		else{
			response = ResponseResult.success(response, result);
		}
		
		return response;
	}
	
	/**
	 * 获取失物招领订单信息
	 * @param parms
	 * @param openId
	 * @param orderNo 订单编号
	 * @return
	 */
	@ApiVersion(value={1})
	public ResponseObject getOrderInfo(Map<String, Object> parms){
		ResponseObject response = ResponseResult.create("lost", "getOrderInfo");
		//参数验证
		if(!checkRequireParms(parms, "openId", "orderNo")){
			return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
		}
		String openId = ConvertUtil.parseString(parms.get("openId"));
		String orderNo = ConvertUtil.parseString(parms.get("orderNo"));
		if(StringUtils.isBlank(openId)){
			return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
		}
		if(StringUtils.isBlank(orderNo)){
			return ResponseResult.exception(response, ErrorCode.ORDER_NO_EMPTY);
		}
		LostOrder query = new LostOrder();
		query.setOrderNo(orderNo);
		
		LostOrder order = lostOrderService.selectOne("", query);
		if(order == null){
			response = ResponseResult.exception(response, ErrorCode.LOST_ORDER_NOT_EXIST);
		}
		else{
			response = ResponseResult.success(response, order);
		}
		return response;
	}
}
